library(ggplot2)
library(dplyr)
library(modelsummary)
library(kableExtra)
library(stringr)
library(fixest)
library(stargazer)
library(gridExtra)
library(flextable)

survey_long <- readRDS("data/df_long.rds")

survey_long <- survey_long %>% filter(d_affiliated == 1 & d_ownparty == 0)
survey_long <- survey_long %>% 
  group_by(meta_UUID) %>%
  mutate(N_ind = n(), 
         weights = meta_Weight / N_ind,
         weights_manual = manual_weights / N_ind) 

party_class <- read.csv("data/cmp_votes.csv") %>% 
  select(evaluated_party, parfam) %>% 
  rename("evaluated_parfam" = "parfam") %>% 
  mutate(eval_parfam_name = evaluated_parfam %>% 
           recode(., 
                  "10" = "Ecological parties", 
                  "20" = "Socialist/left parties",
                  "30" = "Social democratic parties",
                  "40" = "Liberal parties",
                  "50" = "Christian democratic parties",
                  "60" = "Conservative parties", 
                  "70" = "Nationalist parties", 
                  "80" = "Agrarian parties",
                  "90" = "Ethnic and regional parties"
           ))

survey_long <- survey_long %>% left_join(party_class)

party_class <- read.csv("data/cmp_votes.csv") %>% 
  select(party_affil, parfam) %>% 
  rename("affil_parfam" = "parfam") %>% 
  mutate(affil_parfam_name = affil_parfam %>% 
           recode(., 
                  "10" = "Ecological parties", 
                  "20" = "Socialist/left parties",
                  "30" = "Social democratic parties",
                  "40" = "Liberal parties",
                  "50" = "Christian democratic parties",
                  "60" = "Conservative parties", 
                  "70" = "Nationalist parties", 
                  "80" = "Agrarian parties",
                  "90" = "Ethnic and regional parties"
                  ))

survey_long <- survey_long %>% left_join(party_class)


########### Regression analyses

party_df <- survey_long %>% ungroup() %>% 
  select(affil_parfam_name, eval_parfam_name) %>% 
  .[complete.cases(.), ] %>% 
  .[!duplicated(.), ] %>% 
  mutate(coef = NA, 
         se = NA, 
         pvalue = NA)

party_df <- party_df[which(party_df$affil_parfam_name != party_df$eval_parfam_name), ]

models <- list()

for(i in 1:nrow(party_df)){
  
  temp <- survey_long %>% filter(affil_parfam_name == party_df$affil_parfam_name[i] & 
                                   eval_parfam_name == party_df$eval_parfam_name[i])
  
  mod <- feols(close_num ~ feeling_toward + dem_age +  dem_city_or_rural + 
                 dem_gender + high_income + dem_education_level | dem_country_code, temp, 
               weights = temp$weights)
  party_df$coef[i] <- mod$coefficients
  party_df$se[i] <- mod$se[1]
  party_df$pvalue[i] <- as.character(round(mod$coeftable$`Pr(>|t|)`, 3))
  
  #models[[i]] <- mod
  
  print(i)
}

party_df$pvalue <- ifelse(party_df$pvalue == "0", "0.000", party_df$pvalue)
party_df$pvalue <- paste0("(", party_df$pvalue, ")")
# country_df$parties <- factor(country_df$parties, 
#                              levels = country_df$parties[with(country_df, 
#                                                               order(coef))])



pd <- position_dodge(0.5)

regs <- ggplot(party_df, aes(x = affil_parfam_name, ymin = coef - se*1.96, y = coef, ymax = coef + se*1.96, color = eval_parfam_name)) + 
  geom_point(position = pd, shape = 21, fill = 'white') + 
  geom_errorbar(width = 0, position = pd) + 
  geom_hline(yintercept = 0, linetype="dashed", 
             color = "red", size=.4) + 
  #xlab("Respondent party affiliation") + 
  ylab("Feeling coefficient") +
  geom_text(aes(label = pvalue), position = pd, y = 0.62, size = 3.5) +
  coord_flip() +
  ylim(c(-0.3, 0.7)) +
  labs(color='Evaluated party') + 
  facet_wrap(~affil_parfam_name, scales = "free_y") +
  scale_colour_manual(values = c("black", "blue", "green", "cyan2",
                                 "orange2", "brown", "red", "purple")) +
  theme_bw() + 
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank(), 
        legend.position="bottom", text = element_text(size = 14), legend.direction='horizontal') 


regs
ggsave("figures/FigureA5.jpeg", plot = regs,
       height = 10, width = 10, dpi = 600)
